package org.jeecg.common.util;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CustomSort {
    public static void main(String[] args) {
        List<Item> items = Arrays.asList(
            new Item("客厅", "1"),
            new Item("餐厅", "2"),
            new Item("卫生间", "3"),
            new Item("主卧", "4"),
            new Item("次卧", "5")
        );

        List<String> field1Reference = Arrays.asList("客厅", "餐厅", "卫生间", "主卧", "次卧", "书房");
        List<String> field2Reference = Arrays.asList("卫生间", "主卧", "次卧", "餐厅", "客厅");

        List<Item> sortedItemsField1 = customSort(items, Item::getField1, field2Reference, true);
        System.out.println(sortedItemsField1);

    }

    public static <T, S> List<T> customSort(List<T> inputList, Function<T, S> getSortField, List<S> needList, boolean useEquals) {
        Map<S, Integer> indexMap = createIndexMap(needList);

        Comparator<T> customComparator = (item1, item2) -> {
            S field1Value1 = getSortField.apply(item1);
            S field1Value2 = getSortField.apply(item2);

            int score1 = indexMap.getOrDefault(field1Value1, Integer.MAX_VALUE);
            int score2 = indexMap.getOrDefault(field1Value2, Integer.MAX_VALUE);

            return Integer.compare(score1, score2);
        };

        return inputList.stream()
                .sorted(customComparator)
                .collect(Collectors.toList());
    }

    private static <S> Map<S, Integer> createIndexMap(List<S> referenceList) {
        Map<S, Integer> indexMap = new HashMap<>();
        for (int i = 0; i < referenceList.size(); i++) {
            indexMap.put(referenceList.get(i), i);
        }
        return indexMap;
    }

    private static class Item {
        private String field1;
        private String field2;

        public Item(String field1, String field2) {
            this.field1 = field1;
            this.field2 = field2;
        }

        public String getField1() {
            return field1;
        }

        public String getField2() {
            return field2;
        }

        @Override
        public String toString() {
            return "Field1: " + field1 + ", Field2: " + field2;
        }
    }
}
